package com.pfa.test.controllers;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.pfa.test.entities.*;
import com.pfa.test.metier.*;

@Controller
@RequestMapping("/espaceClient")
public class ClientController {
	@Autowired
	private IClientMetier metier;
	
	@RequestMapping(value={"/index"})
	public String index(Model model,HttpServletRequest request, String login){
		try {
			ClientDsi client = metier.getClient(login);
			if(client != null){
				HttpSession session = request.getSession();
				session.setAttribute("login", login);
				session.setAttribute("client", client);
				model.addAttribute("reparations", metier.listReparation(client.getId()));
				return "Client/home";
			}
		} catch (Exception e) {
			return "redirect:/";
		}
		
		return "redirect:/";
	}
	@RequestMapping("/editRep")
	public String editReparation(Model model,HttpServletRequest request){ //Long idRep ,
		
		DemandeReparation d = new DemandeReparation();
				
		d.setStatus("active");
		model.addAttribute("materiels",metier.listMateriel());
		model.addAttribute("pannes",metier.listPanne());
		model.addAttribute("reparation",d);
		return "Client/ajouterReparation";
	}
	@RequestMapping(value="/saveRep",method=RequestMethod.POST)
	public String ajouterReparation(Model model,String oper,HttpServletRequest request,
						@RequestParam String materiel,@RequestParam String panne){
		
		HttpSession session = request.getSession();
		try {
			DemandeReparation d = new DemandeReparation();
			Panne p =metier.getPanneByType(panne);
			Materiel m=metier.getMaterielByType(materiel);
			m.getPannes().add(p);	
			d.setMateriel(m);
			d.setClient(((ClientDsi)session.getAttribute("client")));
			d.setStatus("enCours");
			d.setDateReparation(new Date());
			metier.ajouterReparation(d);	
		} catch (Exception e) {
			model.addAttribute("reparations", metier.listReparation(((ClientDsi)session.getAttribute("client")).getId()));
			return "Client/home";
		}	
		model.addAttribute("reparations", metier.listReparation(((ClientDsi)session.getAttribute("client")).getId()));
		return "Client/home";
	}
	@RequestMapping(value="logout")
	public String logout(Model model,HttpServletRequest request){
		HttpSession session = request.getSession();
		session.invalidate();
		return "page" ; //"redirect:/"
	}
}
